﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace CodeCamp.BL.UI
{
	public static class MvcTagCloud
	{
		private static readonly string[] _Sizes = new[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" };


		public static void ShowTagCloud(this TextWriter output, Dictionary<string, int> data, bool randomize)
		{
			var writer = new HtmlTextWriter(output);
			if (randomize)
			{
				Random r = new Random();
				data = data.OrderBy(_ => r.Next()).ToDictionary(a => a.Key, b => b.Value);
			}
			var quantized = quantize(data);

			renderTagCloud(writer, quantized);
		}

		private static Dictionary<string, int> quantize(Dictionary<string, int> data)
		{
			var result = new Dictionary<string, int>(data.Count);
			if (data != null && data.Count > 0)
			{
				int min = data.Values.Min();
				int max = data.Values.Max();
				double factor = ((min == max ? 1 : max - min)/(float) (_Sizes.Length - 1));
				foreach (var item in data)
				{
					int quantized = (int)Math.Floor((item.Value - min) / factor);
					result[item.Key] = quantized;
				}
			}
			return result;
		}

		private static void renderTagCloud(HtmlTextWriter writer, Dictionary<string, int> data)
		{

			writer.AddAttribute(HtmlTextWriterAttribute.Class, "tag-cloud");
			writer.RenderBeginTag(HtmlTextWriterTag.Div);
			foreach (var item in data)
			{
				writer.AddAttribute(HtmlTextWriterAttribute.Style, "font-size: " + _Sizes[item.Value] + ";");
				writer.RenderBeginTag(HtmlTextWriterTag.Span);
				writer.WriteEncodedText(item.Key);
				writer.RenderEndTag(); // tag span
				writer.Write(" ");

			}

			writer.RenderEndTag(); // outer tag cloud div
		}
	}
}
